<?php

namespace App\HttpController\Api\Device;

use App\HttpController\Api\Base;
use App\Lib\Utils;
use EasySwoole\Component\Di;
use App\Lib\Redis\Redis;
use EasySwoole\Http\Message\Status;
use EasySwoole\FastCache\Cache;

use App\Model\Device\DeviceModel;
use App\Model\Device\Group as GroupModel;
use App\Model\Device\DeviceInfoModel as InfoModel;
use App\Model\Device\DeviceLogModel as LogModel;

use App\Model\Face\FaceModel;
use App\Model\Face\FaceInfoModel;

use App\Model\Device\Carousel as CarouselModel;
use EasySwoole\Component\Timer;
use App\Lib\Curl;
use App\HttpController\FormatSubData;
use App\HttpController\Jvt\Face\UpdateFace as UpdateFaceColl;
use App\HttpController\LogHandel;
use EasySwoole\EasySwoole\Logger;

class Visitor extends \App\HttpController\Api\ApiBase
{

    public $code;
    public $message;
    public $faceObj;
    public $faceInfoObj;
    public $statusCode = 209;

    public function index()
    {
        $getData = $this->raw;
        $actData = json_decode(Utils::characet($getData), true);

        if (isset($actData['methodId']) && !empty($actData['methodId'])) {
            $methodId = $actData['methodId'];
        } else {
            return $this->writeJson($this->statusCode, "methodId 有误", []);
        }

        if (isset($actData['requestData']) && !empty($actData['requestData'])) {
            $data = $actData['requestData'];
        } else {
            return $this->writeJson($this->statusCode, "requestData 有误", []);
        }

        $this->faceObj = new FaceModel();
        $this->faceInfoObj = new FaceInfoModel();

        switch ($methodId) {
            case '1001': $res = self::visitor($data);  break;
            case '1002': $res = self::log($data);  break;
            case '1003': $res = self::delete($data);  break;
            case '1004': $res = self::carousel($data);  break;
            case '1005': $res = self::group($data);  break;
            default: $res = ['code' => $this->statusCode, 'message' => 'methodId未定义', 'data' => new \ArrayObject()];
        }

        return $this->writeJson($res['code'], $res['message'], $res['data']);
    }

    /**
     * 访客信息上传录入
     */
    protected function visitor($reqData)
    {
        if (isset($reqData['deviceSN']) && !empty($reqData['deviceSN'])) {
            $deviceSN = $reqData['deviceSN'];
        } else {
            return ['code' => $this->statusCode, 'message' => '设备唯一码有误', 'data' => new \ArrayObject()];
        }

        if (isset($reqData['deviceIP']) && !empty($reqData['deviceIP'])) {
            $deviceIP = $reqData['deviceIP'];
        } else {
            return ['code' => $this->statusCode, 'message' => '设备IP有误', 'data' => new \ArrayObject()];
        }

        if (isset($reqData['personInfo']) && !empty($reqData['personInfo'])) {
            $personInfo = $reqData['personInfo'];
        } else {
            return ['code' => $this->statusCode, 'message' => '访客信息有误', 'data' => new \ArrayObject()];
        }

        //$configPath = \Yaconf::get('path');
        $configPath = $this->getConfig('path');

        // $condition['companyid'] = $this->userinfo['companyid'];

        $school_code = 1;
        $condition['school_code'] = $school_code;

        try {
            $logger = new LogHandel();

            $data = [];
            $info = [];

            $result = $this->makeData($personInfo);
            if (!$result) {
                return ['code' => $this->code, 'message' => $this->message, 'data' => new \ArrayObject()];
            }

            $data = $result['data'];
            $info = $result['info'];

            $starttime = 9999999999999;
            $endtime = 0;


            $res = $this->checkForDate($reqData, $data, $info, $starttime, $endtime, $companyid);
            if (!$res) {
                return ['code' => $this->code, 'message' => $this->message, 'data' => new \ArrayObject()];
            }

            if (isset($personInfo['facePicture']) && !empty($personInfo['facePicture'])) {
                $image = $reqData['personInfo']['facePicture'];
                $imageName = 'visitor_'.date('YmdHis').mt_rand(10,99).'.jpg';
                $imagePath = EASYSWOOLE_ROOT.$configPath['visitor_path'].date('Ym').'/'.date("d").'/visitor_'.$reqData['deviceSN'];
                $imageAutoDatePath = 0;
                $retData = Utils::saveImage($image, $imageName, $imagePath, $imageAutoDatePath);

                if ($retData['ret'] === 0) {
                    $data['imgpath'] = '/'.ltrim($retData['imgSrc'], EASYSWOOLE_ROOT.'/webroot');
                } else {
                    $data['imgpath'] = '';
                    $logger->log("设备：{$deviceSN}，保存访客图片失败;".$retData['ret'], LogHandel::LOG_LEVEL_INFO, 'Visitor');
                    $logger->log("设备：{$deviceSN}，base64格式;".$image, LogHandel::LOG_LEVEL_INFO, 'Visitor');

                    return [
                        'code' => $this->statusCode,
                        'message' => '保存访客图片失败',
                        'data' => new \ArrayObject()
                    ];
                }
            } else {
                return [
                    'code' => $this->statusCode,
                    'message' => '保存访客图片失败',
                    'data' => new \ArrayObject()
                ];
            }

            if (isset($personInfo['idCardFace'])) {

                $image = $personInfo['idCardFace'];
                $imageName = 'visitorbase_'.date('YmdHis').mt_rand(10,99).'.jpg';
                $imagePath = EASYSWOOLE_ROOT.$configPath['visitor_path'].date('Ym').'/'.date("d").'/visitor_'.$reqData['deviceSN'];
                $imageAutoDatePath = 0;
                $retData = Utils::saveImage($image, $imageName, $imagePath, $imageAutoDatePath);

                if ($retData['ret'] === 0) {
                    $data['imgexpath'] = '/'.ltrim($retData['imgSrc'], EASYSWOOLE_ROOT.'/webroot');
                } else {
                    $data['imgexpath'] = '';
                }
            }

            if (isset($personInfo['telephone'])) {
                $data['phone_number'] = $personInfo['telephone'];
            }

            if ($starttime == 9999999999999) {
                return [
                    'code' => $this->statusCode,
                    'message' => '添加访客失败,访问时间有误',
                    'data' => new \ArrayObject()
                ];
            }

            $data['mode'] = 4;
            $data['school_code'] = $school_code;
            $data['userid'] = 1;
            $data['parentid'] = 0;
            $data['parentpath'] = '0,1,';
            $data['linked'] = 4;
            $data['create_time'] = $data['updatetime'] = time();
            $data['status'] = 1;
            $data['birthday'] = 0;

            $info['limittime'] = 1;
            $info['starttime'] = $starttime;
            $info['endtime'] = $endtime;

            $id = $this->faceObj->add($data);

            if ($id) {
                $info['faceid'] = $id;
                $this->faceInfoObj->add($info);

                /*$udata = $faceObj->getOne('*', ['id' => $id]);
                $updateFaceObj = new UpdateFaceColl();
                $upresult = $updateFaceObj->insert_upface($udata, $action=1, $isend=1, '', 1, 1);*/

                return [
                    'code' => Status::CODE_OK,
                    'message' => '添加访客成功',
                    'data' => new \ArrayObject()
                ];
            } else {
                return [
                    'code' => $this->statusCode,
                    'message' => '添加访客失败',
                    'data' => new \ArrayObject()
                ];
            }
        } catch(\Exception $e) {
            echo $e->getMessage();
            return [
                'code' => Status::CODE_BAD_REQUEST,
                'message' => '系统错误 '.$e->getMessage(),
                'data' => new \ArrayObject()
            ];
        }
    }

    public function makeData($personInfo)
    {
        $data = [];
        $info = [];
        $this->code = 209;

        if (isset($personInfo['name']) && !empty($personInfo['name'])) {
            $data['person_name'] = $personInfo['name'];
        } else {
            $this->message = '访客姓名有误';
            return false;
        }

        if (isset($personInfo['idCardNo']) && !empty($personInfo['idCardNo'])) {
            $data['numbers'] = $personInfo['idCardNo'];
            $info['idcard'] = $personInfo['idCardNo'];
        } else {
            $this->message = '访客身份证有误';
            return false;
        }

        if (isset($personInfo['gender']) && is_numeric($personInfo['gender'])) {
            $data['gender'] = $personInfo['gender'];
        } else {
            $data['gender'] = 1;
        }

        if (isset($personInfo['nation'])) {
            $info['nation'] = $personInfo['nation'];
        } else {
            $info['nation'] = '汉';
        }
        if (isset($personInfo['address'])) {
            $info['addr'] = $personInfo['address'];
        }

        return [
            'data' => $data,
            'info' => $info
        ];
    }

    public function checkForDate($reqData, &$data, &$info, &$starttime, &$endtime, $companyid)
    {
        // 访客每个通行记录的限制时间
        if (isset($reqData['authVisitList']) && !empty($reqData['authVisitList']) && is_array($reqData['authVisitList'])) {
            $authVisitList = $reqData['authVisitList'];
            $area = '';
            $visitorarea = [];
            foreach ($authVisitList as $key => $value) {
                $area .= ','.$value['floorId'];
                $visitorarea[$key]['groupid'] = $value['floorId'];
                $visitorarea[$key]['name'] = $value['floorName'];
                $visitorarea[$key]['beginTime'] = $value['beginTime'];
                $visitorarea[$key]['endTime'] = $value['endTime'];

                // 获取最小的开始时间
                if (strtotime($value['beginTime']) < $starttime) {
                    $starttime = strtotime($value['beginTime']);
                }

                // 获取最大的结束时间
                if (strtotime($value['endTime']) > $endtime) {
                    $endtime = strtotime($value['endTime']);
                }
            }
            $info['visitorarea'] = json_encode($visitorarea);
            $data['area'] = ','.trim($area, ',').',';
        } else {
            $data['area'] = '';
        }

        $isset_where = [];
        $isset_where['A.companyid'] = $companyid;
        $isset_where['A.status'] = 1;
        $isset_where['A.mode'] = 4;
        $isset_where['A.numbers'] = $data['numbers'];

        $result = $this->faceObj->getVisitorIsset('A.id', $isset_where, $starttime, $endtime);
        if ($result) {
            $this->code = 209;
            $this->message = '该时段访客已存在信息，请先删除再添加';
            return false;
        }
        return true;
    }

    /**
     * 查询访客记录
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    protected function log($reqData){

        if(isset($reqData['deviceSN']) && !empty($reqData['deviceSN'])){
            $deviceSN = $reqData['deviceSN'];
        }else{
            return ['code'=>$this->statusCode, 'message'=>'设备唯一码有误', 'data'=>new \ArrayObject()];
        }
        try {
            $columns = 'A.id as visitId, A.name, A.imgpath, A.imgexpath, B.idcard as idCardNo, B.visitorarea';
            $faceObj = new FaceModel();
            if(isset($reqData['pageNumber']) && !empty($reqData['pageNumber'])){
                $pageNumber = intval($reqData['pageNumber']);
            }else{
                $pageNumber = 1;
            }
            $where = [];
            //访客 mode=4
            $where['A.mode'] = 4;

            // $reqData['floorId'] = 1;
            if(isset($reqData['idCardNo']) && !empty($reqData['idCardNo'])){
                $where['A.numbers'] = $reqData['idCardNo'];
            }
            if(isset($reqData['name']) && !empty($reqData['name'])){
                $where['A.name'] = $reqData['name'];
            }
            if(isset($reqData['floorId']) && !empty($reqData['floorId'])){
                $where['A.area'] = ["%,{$reqData['floorId']},%", 'LIKE'];
            }
            if(isset($reqData['beginTime']) && !empty($reqData['beginTime'])){
                $beginTime = strtotime($reqData['beginTime']);

                $where['B.starttime'] = [$beginTime, '>='];
            }
            if(isset($reqData['endTime']) && !empty($reqData['endTime'])){
                $endTime = strtotime($reqData['endTime']);

                $where['B.endtime'] = [$endTime, '<='];
            }
            //获取访客记录
            $data = $faceObj->getFaceData($columns, $where, $pageNumber, $this->params['limit']);


            if($data){
                $lists = [];
                foreach ($data['lists'] as $key => &$value) {

                    $visitorarea = json_decode($value['visitorarea'], true);

                    $authVisitList = [];
                    if(is_array($visitorarea) && (count($visitorarea) > 0)){
                        foreach ($visitorarea as $vkey => $vvalue) {
                            $authVisitList[$vkey]['floorId'] = $vvalue['groupid'];
                            $authVisitList[$vkey]['floorName'] = $vvalue['name'];
                            $authVisitList[$vkey]['beginTime'] = $vvalue['beginTime'];
                            $authVisitList[$vkey]['endTime'] = $vvalue['endTime'];
                        }
                    } 
                    $value['authVisitList'] = $authVisitList;
                    $imgpath = EASYSWOOLE_ROOT.'/webroot'.$value['imgpath'];
                    $imgexpath = EASYSWOOLE_ROOT.'/webroot'.$value['imgexpath'];
                    if(is_file($imgpath)){
                        $imgpath_info = getimagesize($imgpath);
                        $value['facePicture'] = "data:{$imgpath_info['mime']};base64,".chunk_split(base64_encode(file_get_contents($imgpath)));
                    }else{
                        $value['facePicture'] = '';
                    }
                    if(is_file($imgexpath)){
                        $imgexpath_info = getimagesize($imgexpath);
                        $value['idCardFace'] = "data:{$imgexpath_info['mime']};base64,".chunk_split(base64_encode(file_get_contents($imgexpath)));
                    }else{
                        $value['facePicture'] = '';
                    }

                    unset($value['visitorarea']);
                    unset($value['imgpath']);
                    unset($value['imgexpath']);
                }
                $lists['authVisitInfo'] = $data['lists'];
                return ['code'=>Status::CODE_LIST_OK, 'message'=>'获取数据成功', 'data'=>$lists]; 
            }else{
                return ['code'=>$this->statusCode, 'message'=>'无数据', 'data'=>new \ArrayObject()];
            }

        }catch(\Exception $e) {
            echo $e->getMessage();
            return ['code'=>Status::CODE_BAD_REQUEST, 'message'=>'系统错误', 'data'=>new \ArrayObject()];
        }
    }

    /**
     * 删除访客记录
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    protected function delete($reqData){
        if(isset($reqData['deviceSN']) && !empty($reqData['deviceSN'])){
            $deviceSN = $reqData['deviceSN'];
        }else{
            return ['code'=>$this->statusCode, 'message'=>'设备唯一码有误', 'data'=>new \ArrayObject()];
        }
        if(isset($reqData['visitId']) && !empty($reqData['visitId'])){
            $id = $reqData['visitId'];
        }else{
            return ['code'=>$this->statusCode, 'message'=>'visitId 有误', 'data'=>new \ArrayObject()];
        }
        try {
            $faceObj = new FaceModel();
            //删除前获取老数据
            $udata = $faceObj->getOne('*', ['id'=>$id]);
            //执行删除
            $result = $faceObj->destroy($id);
            if($result){
                $infoObj = new FaceInfoModel();
                $infoObj->destroy(['faceid'=>$id]);

                if(file_exists('./webroot'.$udata['imgpath'])){
                    unlink('./webroot'.$udata['imgpath']);
                }

                if(file_exists('./webroot'.$udata['imgexpath'])){
                    unlink('./webroot'.$udata['imgexpath']);
                }
                //通知设备将对应数据删除
                $updateFaceObj = new UpdateFaceColl();
                $updateFaceObj->insert_upface($udata, $action=2, $isend=1);
                return ['code'=>Status::CODE_LIST_OK, 'message'=>'删除成功', 'data'=>new \ArrayObject()];
            }else{
                return ['code'=>$this->statusCode, 'message'=>'删除失败', 'data'=>new \ArrayObject()];
            }
        }catch(\Exception $e) {
            echo $e->getMessage();
            return ['code'=>Status::CODE_BAD_REQUEST, 'message'=>'系统错误', 'data'=>new \ArrayObject()];
        }

    }

    /**
     * 查询轮播图
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    protected function carousel($reqData){
        if(isset($reqData['deviceSN']) && !empty($reqData['deviceSN'])){
            $deviceSN = $reqData['deviceSN'];
        }else{
            return ['code'=>$this->statusCode, 'message'=>'设备唯一码有误', 'data'=>new \ArrayObject()];
        }
        

        // $condition['companyid'] = $this->userinfo['companyid'];
        $condition['companyid'] = 3;
        try {
            $columns = 'id,imgpath,expires,sequence as orders';
            $carouselObj = new CarouselModel();

            $data = $carouselObj->getAll($columns, $condition);
            foreach ($data as $key => $value) {

                $imgpath = EASYSWOOLE_ROOT.'/webroot'.$value['imgpath'];

                $imgpath_info = getimagesize($imgpath);

                $data[$key]['base64'] = "data:{$imgpath_info['mime']};base64,".chunk_split(base64_encode(file_get_contents($imgpath)));
                unset($data[$key]['imgpath']);
                $data[$key]['expires'] = date('YmdHis',$value['expires']);
            }
            if($data){
                $result['visitId'] = $data;
            }else{
                $result['visitId'] = [];
            }
            return ['code'=>Status::CODE_LIST_OK, 'message'=>'成功', 'data'=>$result];
        }catch(\Exception $e) {
            echo $e->getMessage();
            return ['code'=>Status::CODE_BAD_REQUEST, 'message'=>'系统错误', 'data'=>new \ArrayObject()];
        }
    }

    /**
     * 查询楼层分组
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    protected function group($reqData) {
        if(isset($reqData['deviceSN']) && !empty($reqData['deviceSN'])){
            $deviceSN = $reqData['deviceSN'];
        }else{
            return ['code'=>$this->statusCode, 'message'=>'设备唯一码有误', 'data'=>new \ArrayObject()];
        }
        

        // $condition['companyid'] = $this->userinfo['companyid'];
        $condition['companyid'] = 3;
        try {
            $columns = 'id as floorId,name as floorName';
            $groupObj = new GroupModel();

            $data = $groupObj->getAll($columns, $condition);
            if($data){
                $result['floorList'] = $data;
            }else{
                $result['floorList'] = [];
            }
            return ['code'=>Status::CODE_LIST_OK, 'message'=>'成功', 'data'=>$result];
        }catch(\Exception $e) {
            echo $e->getMessage();
            return ['code'=>Status::CODE_BAD_REQUEST, 'message'=>'系统错误', 'data'=>new \ArrayObject()];
        }
    }
}